#include <omp.h>
#include <stdio.h>

int main() {
    int data;
    int flag = 0;

    #pragma omp parallel num_threads(2)
    {
        int thread_num = omp_get_thread_num();

        if (thread_num == 0) {
            // 线程 0 写入数据并设置标志
            data = 42;
            printf("Thread %d: Setting data to 42\n", thread_num);
            #pragma omp flush(flag, data) // 确保数据和标志对线程 1 可见
            printf("Thread %d: Flushed data and flag\n", thread_num);
            #pragma omp atomic write
            flag = 1;
            printf("Thread %d: Setting flag to 1\n", thread_num);
        } else if (thread_num == 1) {
            // 线程 1 等待标志变为 1
            int flag_val = 0;
            while (flag_val < 1) {
                #pragma omp atomic read
                flag_val = flag;
                if (flag_val < 1) {
                    printf("Thread %d: Waiting for flag to become 1 (current flag: %d)\n", thread_num, flag_val);
                }
            }
            // 打印数据（此时数据可能未定义）
            printf("Thread %d: Flag is now 1, data before flush: %d\n", thread_num, data);
            #pragma omp flush(flag, data) // 确保数据和标志对线程 0 可见
            // 打印数据（此时数据应为 42）
            printf("Thread %d: After flush, data: %d\n", thread_num, data);
        }
    }

    return 0;
}
